import { connect } from 'umi';
import { useEffect } from 'react';
import { useTRState } from '#/utils/trHooks.jsx';
import moment from 'moment';

import styles from './index.less';
import { Button, DatePicker, Radio, Select } from 'antd';
import TradeCenterTime from '../TradeCenterTime';
import HeadRight from '../HeadRight';
import { TRMessage } from '#/components';

import { tradeOptions } from '../../constant';
import { getTimeSlot, getTimesPoint } from '../../helper';
import { queryMarketList, queryPlanInfo } from '../..//services';
import { HttpCode } from '#/utils/contacts.js';
import { getTreeByCodes } from '@/utils';

const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
const timeSolt = getTimeSlot();

const Header = ({
  menuCode,
  powerLimitInfo,
  dispatch,
  hasSave,
  setLoading,
  marketList,
  provinceId,
  marketId,
}) => {
  const [state, setState] = useTRState({
    provinceId: '', // 交易省份id
    date: moment(), // 交易日
    hourOrder: '', // 日内选择时间段
    type: 'dayahead', // 日前 dayahead 日内 intraday
    intraDayDate: [moment(), moment()],
    marketList: [], //省份数组
    marketId: '',
    times_config: timeSolt,
  });
  const handleSearch = async (params = {}) => {
    if (!!params?.marketList && params?.marketList.length < 1) {
      return;
    }
    setLoading(true);
    let date;
    // 点击搜索
    const times = [
      state.intraDayDate[0].format(dateFormat),
      state.intraDayDate[1].format(dateFormat),
    ];
    date = times.toString();
    let param = {
      provinceId: !!params?.provinceId ? params.provinceId : state.provinceId,
      hourOrder: state.hourOrder,
      type: state.type,
      marketId: !!params?.marketId ? params.marketId : state.marketId,
      date,
    };
    const res = await queryPlanInfo(param);
    if (res.statusCode === HttpCode.SUCCESS) {
      let obj = { ...state, date };
      delete obj['times_config'];
      dispatch({
        type: 'interprovincialSpotDeclaration/setSearchData',
        payload: {
          ...param,
          startOrder: res?.startOrder || '',
          endOrder: res?.endOrder || '',
          marketList: !!params.marketList ? params.marketList : state.marketList,
          planData: res?.dataList || [],
          hasSave: false,
        },
      });
    } else {
      TRMessage.error(res?.message || '获取方案列表失败！');
    }
    setState({
      ...state,
      provinceId: !!params?.provinceId ? params.provinceId : state.provinceId,
      marketList: !!params.marketList ? params.marketList : state.marketList,
      marketId: !!params.marketId ? params.marketId : state.marketId,
    });
    setLoading(false);
  };
  useEffect(() => {
    if (hasSave) {
      dispatch({
        type: 'interprovincialSpotDeclaration/setAddLoadingNum',
      });
      if (marketList.length !== 0) {
        fetch({ marketList: marketList, provinceId: provinceId, marketId: marketId });
      } else {
        fetch();
      }
    }
  }, [hasSave]);

  const fetch = async (data) => {
    if (data) {
      await handleSearch(data);
    } else {
      // 获取省份和场站信息
      const res = await queryMarketList(menuCode);
      if (res && res.statusCode === HttpCode.SUCCESS) {
        const power = getTreeByCodes(['market', 'group', 'station'], res.json).treeOptions;
        let obj = {
          marketList: power,
          marketId: power.length > 0 ? power[0].value : '',
          provinceId: power.length > 0 ? power[0].provinceId : '',
        }; // 设置默认场站
        await handleSearch(obj);
      } else {
        TRMessage.error(res?.message || '获取交易省份列表失败！');
      }
    }
  };
  const getTimesConfig = () => {
    // 获取日内可选时间段
    let hourOrder;
    let now_point = Math.floor(getTimesPoint() / 8) * 8 + 1; // 获取当前时间段初始时间
    timeSolt.map((item) => {
      if (now_point + 16 >= item.points[0]) {
        hourOrder = item.value;
        ``;
      }
    });
    setState({ hourOrder });
  };
  const onTypeChange = ({ target: { value } }) => {
    // 更改日内日前状态
    if (value !== 'dayahead') {
      getTimesConfig();
    }
    setState({ type: value });
  };

  return (
    <div className={styles.header}>
      <div className={styles.condition}>
        <Select
          className={styles.provinceSelect}
          showSearch={true}
          filterOption={(inp, option) => option.label.includes(inp)}
          value={state.marketId}
          options={state.marketList}
          onChange={(value, opt) => {
            setState({ provinceId: opt.provinceId, marketId: value });
          }}
        />
        <Radio.Group
          className={styles.radioGroup}
          options={tradeOptions}
          onChange={onTypeChange}
          value={state.type}
          optionType="button"
          buttonStyle="solid"
        />
        <RangePicker
          className={styles.rangePicker}
          value={state.intraDayDate}
          format={[dateFormat, dateFormat]}
          onChange={(value) => {
            setState({ intraDayDate: value });
          }}
        />
        {/*{state.type === 'intraday' ? (*/}
        {/*    <RangePicker*/}
        {/*        className={styles.rangePicker}*/}
        {/*        value={state.intraDayDate}*/}
        {/*        format={[dateFormat, dateFormat]}*/}
        {/*        onChange={(value) => {*/}
        {/*            setState({intraDayDate: value});*/}
        {/*        }}*/}
        {/*    />*/}
        {/*) : (*/}
        {/*    <DatePicker*/}
        {/*        className={styles.dataPicker}*/}
        {/*        allowClear={false}*/}
        {/*        value={state.date}*/}
        {/*        format="YYYY.MM.DD"*/}
        {/*        onChange={(value) => {*/}
        {/*            if (state.type !== 'dayahead' && moment().isSame(value, 'd')) {*/}
        {/*                getTimesConfig();*/}
        {/*            }*/}
        {/*            setState({date: value});*/}
        {/*        }}*/}
        {/*    />*/}
        {/*)}*/}
        <Button className={styles.queryBtn} type="primary" onClick={() => handleSearch()}>
          查询
        </Button>
      </div>
      <TradeCenterTime />
      <HeadRight />
    </div>
  );
};

export default connect(({ global, interprovincialSpotDeclaration }) => ({
  menuCode: global.configure.menuCode,
  powerLimitInfo: interprovincialSpotDeclaration.powerLimitInfo,
  hasSave: interprovincialSpotDeclaration.hasSave,
  marketList: interprovincialSpotDeclaration.marketList,
  provinceId: interprovincialSpotDeclaration.provinceId,
  marketId: interprovincialSpotDeclaration.marketId,
}))(Header);
